<?php

namespace co2\dev\v0_0_0;

class bash

{
	protected
		$cmd,
		$output,
		$user
		;
		
	public function
	__construct
	(
		$cmd
	)
	
	{
		$this->cmd=$cmd;
		$this->user=trim(`whoami`);
	}
		
	public function
	exec
	(
		$expect=null
	)
	{
		$this->output=trim(`$this->cmd 2>&1`);
		
		if(is_null($expect))
		$expect=new RegEx('/.?/');

		if($expect instanceof RegEx)
		$success=preg_match((string)$expect,$this->output);

		else
		$success=$this->output==$expect;
		
		if(!$success)
		
		{
		  $message='Failed to run command `'.$this->cmd.'` as '.$this->user.', terminal said: '.$this->output;
		  $debug=(object)array('command'=>$this->cmd,'user'=>$this->user,'output'=>$this->output);
		  $level=0;
		  
		  if(isset($this->errors))
		  
		  {
		    foreach($this->errors as $k=>$v)
		    if(preg_match($v,$this->output))
		    {
		      $level=$k;
		    }
		  }

		  throw new Exception($message,$debug,$level);
		}
		
		return $this->output;
	}
	
	public function
	__toString
	()
	
	{
		return $this->cmd;
	}
}
